package com.fhao.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.logging.Log;
import com.alipay.api.AlipayApiException;
import com.fhao.feign.CallBackServiceFeign;
import com.fuhao.base.ResponseBase;
import com.fuhao.constants.Constants;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/alibaba/callBack")
public class CallBackController {
	
	@Autowired
	private CallBackServiceFeign callBackServiceFeign;
	
	/**
	 * 同步通知
	 * @throws IOException 
	 */
	@RequestMapping("/returnUrl")
	public void synCallBack(HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		//获取支付宝GET过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		log.info("########支付宝同步回调CallBackController开始,param{}:"+params);
		ResponseBase synCallBack = callBackServiceFeign.synCallBack(params);
		if(!synCallBack.getCode().equals(Constants.HTTP_RES_CODE_200)) {
			//返回到报错页面
			request.setAttribute("error", "同步回调异常");
		}
		LinkedHashMap data = (LinkedHashMap) synCallBack.getData();
		String htmlFrom = "<form name='punchout_form'"
				+ " method='post' action='http://127.0.0.1/alibaba/callBack/synSuccessPage' >"
				+ "<input type='hidden' name='outTradeNo' value='" + data.get("outTradeNo") + "'>"
				+ "<input type='hidden' name='tradeNo' value='" + data.get("tradeNo") + "'>"
				+ "<input type='hidden' name='totalAmount' value='" + data.get("totalAmount") + "'>"
				+ "<input type='submit' value='立即支付' style='display:none'>"
				+ "</form><script>document.forms[0].submit();" + "</script>";
		writer.println(htmlFrom);
		writer.close();
		log.info("########支付宝同步回调CallBackController结束,param{}:"+params);
	}
	//解决同步回调的参数?拼接在url中
	//通过post隐藏方法
	@RequestMapping(value="/synSuccessPage",method = RequestMethod.POST)
	public String synSuccessPage(HttpServletRequest request,String outTradeNo,String tradeNo,String totalAmount) {
//		String error = request.getParameter("error");
//		if(!StringUtils.isEmpty(error)) {
//			request.setAttribute("error", error);
//			return "error";
//		}
		//商户订单号
		request.setAttribute("outTradeNo", outTradeNo);
		//支付宝交易号
		request.setAttribute("tradeNo", tradeNo);
		//付款金额
		request.setAttribute("totalAmount", totalAmount);
		return "pay_success";
	}
	
	/**
	 * 异步通知
	 * 返回seccess给支付宝
	 */
	@RequestMapping("/notifyUrl")
	@ResponseBody
	public String asynCallBack(HttpServletRequest request,HttpServletResponse response) {
		Map<String, String> params = new HashMap<String, String>();
		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
//			// 乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		log.info("###支付宝异步回调CallBackController####synCallBack开始 params:{}", params);
		String result;
		try {
			result = callBackServiceFeign.asynCallBack(params);
		} catch (AlipayApiException e) {
			log.info("控制成异步验签异常");
			e.printStackTrace();
			return "error";
		}
		log.info("#####支付异步回调结果####result="+result);
		return result;
	}
}

